package com.moonstar.controller;

import com.moonstar.pojo.FriendDO;
import com.moonstar.pojo.Result;
import com.moonstar.pojo.User;
import com.moonstar.service.FriendService;
import com.moonstar.service.UserService;
import com.moonstar.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *
 *
 *
 */
@Controller
@RequestMapping("/friend")
public class FriendController {

	@Autowired
	private FriendService friendService;
	@Autowired
	private UserService userService;

	@ResponseBody
	@GetMapping("/list")
	public List<FriendDO> list(@RequestParam Map<String, Object> params){
		params.put("offset", 0);
		params.put("limit", 100);
		//查询列表数据
        Query query = new Query(params);
		List<FriendDO> friendList = friendService.list(query);
		return friendList;
	}

	@GetMapping("/edit/{id}")
	public String toEdit(Model model, @PathVariable("id") Long id){
		model.addAttribute("selfId", id);
	    return "addFriend";
    }

	/**
	 * 保存，加好友，需要双向加，保存两条数据
	 */
	@ResponseBody
	@PostMapping("/save")
	public Result save(String selfId, String friendId){
		User friend = userService.get(Long.valueOf(friendId));
		if(friend.getId().toString().equals(selfId)){
			return Result.error("不能加自己为好友");
		}

		HashMap<String, Object> map = new HashMap<>();
		map.put("selfId", Long.valueOf(selfId));
		map.put("friendId", friendId);
		List<FriendDO> list = friendService.list(map);
		if(!list.isEmpty()){
			return Result.error("不能重复添加好友");
		}

		FriendDO friendDO = new FriendDO();
		friendDO.setSelfId(Integer.parseInt(selfId));
		friendDO.setFriendId(Integer.valueOf(friendId));
		friendDO.setFriendName(friend.getUsername());
		int save = friendService.save(friendDO);

		FriendDO friendDO1 = new FriendDO();
		friendDO1.setSelfId(Integer.valueOf(friendId));
		friendDO1.setFriendId(Integer.valueOf(selfId));
		User self = userService.get(Long.valueOf(selfId));
		friendDO1.setFriendName(self.getUsername());
		int save1 = friendService.save(friendDO1);

		if(save>0 && save1>0){
			return Result.success();
		}
		return Result.error();
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	public Result remove(Integer id){
		if(friendService.remove(id)>0){
			return Result.success();
		}
		return Result.error();
	}

}
